package com.aliang.shopping.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.aliang.shopping.common.Result;
import com.aliang.shopping.common.ResultCodeEnum;
import com.aliang.shopping.contact.ResultMsgContact;
import com.aliang.shopping.contact.SqlColumnConstant;
import com.aliang.shopping.exception.DataException;
import com.aliang.shopping.model.dto.common.UpdateStatusDTO;
import com.aliang.shopping.model.po.Contact;
import com.aliang.shopping.model.po.Message;
import com.aliang.shopping.model.vo.chat.ContactVO;
import com.aliang.shopping.model.vo.chat.MessageVO;
import com.aliang.shopping.security.auth.UserHolder;
import com.aliang.shopping.service.ContactService;
import com.aliang.shopping.service.MessageService;
import com.aliang.shopping.util.InputDataUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;


@RestController
@RequestMapping("/chat")
@AllArgsConstructor
public class ChatController {

    private final ContactService contactService;
    private final MessageService messageService;

    @GetMapping("/get_contact_list")
    @ApiOperation("查询联系人列表")
    public Result<List<ContactVO>> getContactList(String keyword) {
        List<ContactVO> result = this.contactService.getContactList(keyword);
        return Result.ok(result);
    }

    @GetMapping("/get_message_List/{contactId}")
    @ApiOperation("根据联系人Id获取消息列表")
    public Result<List<MessageVO>> getMessageList(@PathVariable("contactId") Long contactId) {
        List<MessageVO> result = this.messageService.getMessageListByContactId(contactId);
        return Result.ok(result);
    }

    @PutMapping("/update_unread_num/{contactId}")
    @ApiOperation("根据联系人Id更新未读数")
    public Result<String> updateUnreadNum(@PathVariable("contactId") Long contactId) {
        //获取当前登录用户Id
        Long userId = UserHolder.getUserId();
        //根据用户Id和联系人Id修改未读数
        boolean result = this.contactService.update(
                new LambdaUpdateWrapper<Contact>()
                        //设置sql
                        .setSql("unread = unread + 1")
                        .eq(Contact::getUserId, userId)
                        .eq(Contact::getContactId, contactId)
        );
        return result ? Result.ok("") : Result.fail();
    }

    @PostMapping("/add_contact/{contactId}")
    @ApiOperation("添加联系人")
    public Result<String> addContact(@PathVariable("contactId") Long contactId) {
        //获取当前登录用户Id
        Long userId = UserHolder.getUserId();
        // 判断是否已添加联系人
        int count = this.contactService.count(new LambdaQueryWrapper<Contact>()
                .eq(Contact::getUserId, userId)
                .eq(Contact::getContactId, contactId)
        );
        //已添加，直接返回
        if (count > 0) {
            return Result.ok("");
        }
        // 封装数据
        // 用户添加联系人
        Contact user = new Contact();
        user.setContactId(contactId);
        user.setUnread(0);
        user.setLastSendTime(System.currentTimeMillis());
        user.setUserId(userId);
        //商家添加联系人
        Contact business = new Contact();
        business.setContactId(userId);
        business.setUnread(0);
        business.setLastSendTime(System.currentTimeMillis());
        business.setUserId(contactId);
        //批量添加联系人
        boolean save = this.contactService.saveBatch(Arrays.asList(user, business));
        //添加问候语
        Message message = new Message();
        message.setId(UUID.randomUUID().toString(true));
        message.setType("text");
        message.setSendTime(System.currentTimeMillis());
        message.setContent("欢迎光顾小店，请问有什么能帮到您的？");
        message.setStatus("success");
        message.setToId(userId);
        message.setFromId(contactId);
        message.setDeleteId(0L);

        return save ? Result.ok("") : Result.fail(ResultMsgContact.INSERT_FAIL);
    }

    @PutMapping("/update_contact_status")
    @ApiOperation("修改联系人置顶状态")
    public Result<String> updateContactTopStatus(UpdateStatusDTO updateDTO) {
        //必要字段校验
        if (BeanUtil.isEmpty(updateDTO)) {
            throw new DataException(ResultCodeEnum.DATA_LACK);
        }
        // 状态数字合法性校验
        if (!InputDataUtil.numIsOK(updateDTO.getStatus())) {
            throw new DataException(ResultCodeEnum.TYPE_NUM_ERR);
        }
        //获取当前登录用户Id
        Long userId = UserHolder.getUserId();
        // 封装数据
        Contact contact = new Contact();
        contact.setIsTop(updateDTO.getStatus());
        //根据用户Id和联系人Id修改置顶状态
        boolean save = this.contactService.update(contact, new LambdaUpdateWrapper<Contact>()
                .eq(Contact::getUserId, userId)
                .eq(Contact::getContactId, updateDTO.getId()));
        return save ? Result.ok("") : Result.fail(ResultMsgContact.INSERT_FAIL);
    }


    @DeleteMapping("/delete_contact/{contactId}")
    @ApiOperation("删除联系人")
    public Result<String> deleteContact(@PathVariable("contactId") Long contactId) {
        this.contactService.remove(new QueryWrapper<Contact>().eq(SqlColumnConstant.CONTACT_ID, contactId));
        //删除信息
        Long userId = UserHolder.getUserId();
        this.messageService.removeBYUserIdAndContactId(userId, contactId);
        return Result.ok(ResultMsgContact.DELETE_SUCCESS);
    }

    @GetMapping("/getUnreadMessage")
    @ApiOperation("获取未读数")
    public Result<Integer> getUnreadMessage() {
        // 获取当前登录用户Id
        Long userId = UserHolder.getUserId();
        Integer num = this.contactService.getUnreadNum(userId);
        return Result.ok(num);
    }

    @DeleteMapping("/delete_message")
    @ApiOperation("删除消息")
    public Result<String> deleteMessage(String id) {
        //根据Id获取信息
        Message byId = this.messageService.getById(id);
        if (Objects.isNull(byId)) throw new DataException(ResultCodeEnum.DATA_LACK);
        if (Objects.isNull(byId.getDeleteId())) {
            // 没有被删除，设置删除方Id
            Message message = new Message();
            message.setId(id);
            message.setDeleteId(UserHolder.getUserId());
            // 更新数据
            this.messageService.updateById(message);
        } else {
            // 已经被删除，删除数据
            this.messageService.removeById(id);
        }
        return Result.ok(ResultMsgContact.DELETE_SUCCESS);
    }
}
